package com.zzh.partnersys.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.zzh.partnersys.config.AliPayZhiFuBaoConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author �?�?�?
 * @version 1.0
 */
@RestController
@RequestMapping("/alipay")
public class ZhiFuBaoController {
    //注入配置�?从配置类获取相关信息)
    @Resource
    private AliPayZhiFuBaoConfig aliPayConfig;

    //支付宝接口的网关地址，正�?https://openapi.alipay.com/gateway.do"
    String serverUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    //返回格式(只支持json)
    String Format = "json";

    //编码�?
    String CHARSET = "utf-8";

    //签名算法类型
    String SIGN_TYPE = "RSA2";


    //测试
    @GetMapping("/hello")
    public String test(){
        return "hello";
    }

    //当点击支付时调用该接口，该接口会去请求支付宝去进行一个请�?传一个订单编�?
    @GetMapping("/pay")
    public void pay(String orderNo, HttpServletRequest httpRequest,
                    HttpServletResponse httpResponse) throws IOException {
        System.out.println("orderNo:"+orderNo);
        //通过订单编号查询数据库相关信�?金额)
        //模拟一个数据库查询出来�?订单Order对象
//        String tradeNo = orderNo;//如果之前用过就不能用了，要改掉这个�?
        String tradeNo = "12344422234441";//如果之前用过就不能用了，要改掉这个�?
        Double totalAmount = 99.99;
        String subject = "小米手机";


        //1. 构造sdk的客户端对象(都是支付宝提供的接口对象) //调用支付宝的请求
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl,aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(),Format,CHARSET,aliPayConfig.getAlipayPublicKey(),SIGN_TYPE);

        //2.创建 request 请求设置 request的参�?
        AlipayTradeWapPayRequest aliPayRequest = new AlipayTradeWapPayRequest();
        aliPayRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());//设置支付成功后回调的接口
        aliPayRequest.setReturnUrl(aliPayConfig.getReturnUrl());//支付宝支付成功后返回的页面（前端订单页面�?

        //封装一些参数到BizContent整体
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",tradeNo);// 传入一个订单号(数据库拿)(订单编号不能重复的要唯一)
        bizContent.put("total_amount",totalAmount);// 传入一个支付的总金�?
        bizContent.put("subject",subject);// 传入一个支付的名称(可以传一个商品名)
        bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");// 固定�?
        aliPayRequest.setBizContent(bizContent.toString());

        String form="";
        try {
            //请求支付宝下单接�?发起http请求
            form = alipayClient.pageExecute(aliPayRequest).getBody(); //调用SDK生成表单
            System.out.println("form"+form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //回写页面(浏览器会直接映射表单呈现出来)
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页�?
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    //点击支付完成的按钮后 回调
    @GetMapping("/returnCallBack")
    public String returnCallBack(HttpServletRequest httpRequest){
        //http://n8eaccf6.natappfree.cc/partner/alipay/returnCallBack
        // ?charset=utf-8
        // &out_trade_no=12344422234441
        // &method=alipay.trade.wap.pay.return
        // &total_amount=99.99
        // &sign=LhlCTPfOXHJ6NZMY3d183jLNOaYgFw03GvhiDsqIBGxE9TmEKHsDn64UyhvkP1kTk%2BA0umUzwPePjBeW73Nq4QWrMeG01M9lcJIBTxUkLi3vYS8uBxoA3T0UOrABk2wuLxY8poEsCWlMgjdCBoSJ1GMuexVYpd8Oh6sCKZ7b3uw8maVP6UuSuHGPc0eTmDOPDxmSnMod%2FG%2BeZ7etK%2BJd%2BJbYnt30rsD0SU%2BL1BjQ5K%2Fua4Sag1KElmygka76qekGSOKgxrrGRlH5UnQyGHizfOykHNBOu9Hg9k3hF%2BErAT4ApNgps12K1CdxKT02ZxxQU%2BUNMPWUEpUI04S95C7iRA%3D%3D
        // &trade_no=2025091722001434570507205882
        // &auth_app_id=9021000136699791
        // &version=1.0
        // &app_id=9021000136699791
        // &sign_type=RSA2
        // &seller_id=208872103561905
        // 1&timestamp=2025-09-17+23%3A49%3A45
        String outTradeNo = httpRequest.getParameter("out_trade_no");
        System.out.println("outTradeNo:"+outTradeNo);
        return "returnCallBack";
    }


    //支付成功回调通知接口=》可以去修改订单状�?
    @PostMapping("/notify") // 必须是post请求
    public void paySuccessNotify(HttpServletRequest httpRequest){
        String outTradeNo = httpRequest.getParameter("out_trade_no");
        String tradeStatus = httpRequest.getParameter("trade_status");
        System.out.println("outTradeNo:"+outTradeNo);//上次的订单编�?
        System.out.println("tradeStatus:"+tradeStatus);//TRADE_SUCCESS
        //这里就可以直接去获取订单，修改订单状�?
        if("TRADE_SUCCESS".equals(tradeStatus)){
            //修改订单状�?
            System.out.println("notify");
        }
    }

}